<?php
namespace Addons\Redguest\Controller\Admin;
use Lib\Response;
use Session;
use Models\BaseModel as Model;
use Addons\QyWechat\Services\QyWechatApi;
use Addons\QyWechat\Helper;

class Envelopes extends \BaseController
{
    public function index(){
        $wid = \Session::get("wid");
        $confing  = (new Model("qy_envelopes_confing"))->find(["wid"=>$wid]);
        $cover  = (new Model("qy_red_cover"))->find(["wid"=>$wid]);
        $p = new \Pagination(); 
        $redguest = $p->model_list((new Model("qy_redguest"))->where(["wid"=>$wid]));
        $this->assign("redguest",$redguest);
        $this->assign("confing",$confing);
        $this->assign("cover",$cover);
        $this->assign("p", $p);
        $this->assign("P", $GLOBALS['P']);
        return $this->show();
    }

    public function data_base(){
        $wid = \Session::get("wid");
        $p = new \Pagination();  
        $confing  = (new Model("qy_envelopes_confing"))->find(["wid"=>$wid]);
        $cover  = (new Model("qy_red_cover"))->find(["wid"=>$wid]);
        $prices = array_unique(array_column((new Model("qy_redguest_list"))->where(["wid"=>$wid,"price@!="=>""])->field("price")->list_all_array(),"price"));
        $where["wid"] = $wid;
        $username = \Request::get("username");
        $price = \Request::get("price");
        $number = \Request::get("number");
        $time = \Request::get("time");
        if($username){
            $list_alls = array_column((new \Model('qy_externalcontact_list'))->where(['name@~'=>$username])->field("id,name")->list_all_array(),"id");
            $where['userid'] = $list_alls;
        }
        if($price){
            $where['price'] = $price;
        }
        if($number){
            $where['status'] = $number;
        }
        if($time){
            $ktime = strtotime(substr($time, 0,-13));
            $jtime = strtotime(substr($time, -10));
            $where['ctime@>='] = $ktime;
            $where['ctime@<='] = $jtime+3600*24;
        }
        $list = $p->model_list((new Model("qy_redguest_list"))->where($where));
        foreach ($list as $key => $value) {
            $list[$key]->redguest = (new Model("qy_redguest"))->find(["id"=>$value->pid]);
            $list[$key]->user = (new Model("qy_externalcontact_list"))->find(["id"=>$value->userid]);
        }
        $this->assign("p", $p);
        $this->assign("P", $GLOBALS['P']);
        $this->assign("username",$username);
        $this->assign("pricese",$price);
        $this->assign("number",$number);
        $this->assign("time",$time);
        $this->assign("cover",$cover);
        $this->assign("list",$list);
        $this->assign("prices",$prices); 
        $this->assign("confing",$confing);
        return $this->show();
    }

    public function update_red_confing(){
        setApi();
        $wid = \Session::get("wid");
        $red_id = $_POST["red_id"];
        $red_title = $_POST["red_title"];
        $red_content = $_POST["red_content"];
        $red_file = $_POST["red_file"];
        if($red_id){
            $cover = (new Model("qy_red_cover"))->find($red_id);
        }else{
            $cover = new Model("qy_red_cover");
        }
        $cover->red_title = $red_title;
        $cover->red_content = $red_content;
        $cover->red_image = $red_file;
        $cover->wid = $wid;
        $cover->save();
        if($cover->id){
            sendSuccess("修改成功");
        }
        sendError("修改失败");
    }

    public function add(){
        $wid = \Session::get("wid");
        $name = \Request::get("name");
        $sexs = \Request::get("sexs");
        $price = \Request::get("price");
        $size = \Request::get("size");
        $greeting = \Request::get("greeting");
        $get = \Request::get("get");
        $area = \Request::get("areasetting");
        // $province = \Request::get("province");
        // $city = \Request::get("city");
        // $county = \Request::get("county");
        $lng = \Request::get("lng");
        $lat = \Request::get("lat");
        $address = \Request::get("address");
        $distance_range = \Request::get("distance_range");
        if (!is_numeric($price) || !is_numeric($size)){
            echo "<script>alert('bu是数字');history.go(-1);</script>";die;
        }
        if($price <0.3 || $size < 1){
            echo "<script>alert('金额最低不能低于0.3 红包数量不能低于1');history.go(-1);</script>";die;
        }
        $redguest  = new Model("qy_redguest");
        $redguest->wid = $wid; 
        $redguest->red_name = $name;
        $redguest->red_status = $sexs;
        $redguest->red_price = $price;
        $redguest->red_size = $size;
        $redguest->red_greeting = $greeting;
        $redguest->red_get = $get;
        $redguest->red_area = $area;
        $redguest->status = 1;
        $redguest->ctime = time();
        $redguest->lng = $lng;
        $redguest->lat = $lat;
        $redguest->address = $address;
        $redguest->distance_range = $distance_range;
        // $redguest->area = $province.'-'.$city.'-'.$county;
        $redguest->save();
        if($redguest->id){
            echo "<script>alert('创建成功');window.location.href='index.html';</script>";die;
        }else{
            echo "<script>alert('创建失败');history.go(-1);</script>";die;
        }
    }
    public function dehb(){
        setApi();
        $id = \Request::post("id");
        $data = (new \Model('qy_redguest'))->id($id);
        $del = $data->remove();
        if($del){
            sendSuccess('删除成功');
        }else{
            sendError('删除失败');
        }
    }

    public function uphb(){
        $id = \Request::get("id");
        $redguest = (new \Model('qy_redguest'))->find(["id"=>$id]);
        // $area = explode("-", $redguest->area);
        if(is_post()){
            setApi();
            $str = explode("&",$_POST["params"]);
             foreach($str as $key=>$value){
                $arr = explode("=",$value);
                $output[$arr[0]] = $arr[1];
            }
            $name = $output["name"];
            $sexs = $output["sexss"];
            $price = $output["price"];
            $size = $output["size"];
            $greeting = $output["greeting"];
            $get = $output["get"];
            $area = $output["areasetting"];
            // $province = $output["province"];
            // $city = $output["city"];
            // $county = $output["county"];
            $lng = $output["lng"];
            $lat = $output["lat"];
            $address = $output["address"];
            $distance_range = $output["distance_range"];
            $redguest->red_name = $name;
            $redguest->red_status = $sexs;
            $redguest->red_price = $price;
            $redguest->red_size = $size;
            $redguest->red_greeting = $greeting;
            $redguest->red_get = $get;
            $redguest->red_area = $area;
            $redguest->lng = $lng;
            $redguest->lat = $lat;
            $redguest->address = $address;
            $redguest->distance_range = $distance_range;
            if($redguest->save()){
                sendSuccess('修改成功');
            }
            sendError('修改失败');
        }
        $this->assign("redguest",$redguest);
        // $this->assign("area",$area);
        return $this->show();
    }

     public function ting(){
        setApi();
        $id = \Request::post("id");
        $data = new \Model('qy_redguest');
        $upd = $data->update(['id'=>$id],['status'=>0]);
        if($upd){
            sendSuccess('操作成功');
        }
        sendError('操作失败');
    }

    public function upd_status(){
        setApi();
        $id = \Request::post("id");
        $data = new \Model('qy_redguest');
        $upd = $data->update(['id'=>$id],['status'=>1]);
        if($upd){
            sendSuccess('操作成功');
        }
        sendError('操作失败');
    }

    public function add_file(){
        setApi();
        $id = \Session::get("wid");
        $path = './cert/cert-'.$id;
        $field = 'file';
        if (!$_FILES[$field]) sendError('文件不存在');
        $ext = explode('.', $_FILES[$field]["name"]);
        $ext = $ext[count($ext) - 1];
        // 创建文件夹
        try {
            mkdir($path, 0777, true);
        } catch (\Exception $e) {
            // 防止文件夹已存在
        }
        $path = $path . '/' . md5_file($_FILES[$field]['tmp_name']) . '.' . $ext;
        $saveImg = move_uploaded_file($_FILES[$field]['tmp_name'], $path);
        if($saveImg){
            $filePath = $saveImg ? $path : $saveImg;
            $str=ltrim($filePath,".");
            sendSuccess('上传成功',['filePath'=>$str,'fileName'=>$_FILES[$field]["name"]]);
        }else{
            sendError('上传失败');
        }
    }


    public function update_confing(){
        setApi();
        $id = \Session::get("wid");
        $confing = (new \Model('qy_envelopes_confing'))->find(["wid"=>$id]);
        $confing->status = $_POST['status'];
        $confing->mchid = $_POST['mchid'];
        $confing->apiKey = $_POST['apiKey'];
        $confing->cert_one = $_POST['cert_one'];
        $confing->cert_tow = $_POST['cert_tow'];
        $confing->wid = $id;
        $confing->save();
        sendSuccess('修改成功');
    }

    public function customer_info(){
        $wid = \Session::get('wid');
        $etId = \Request::get(1);
        $r_user_id = Session::get('r_user_id');
        $et = (new Model('qy_externalcontact_list'))->find($etId);
        $message = (new Model('qy_messageset'))->find(["wid"=>$wid]);
        $et->tags = json_decode($et->tags,1);
        $et->remark_mobiles = implode(",",json_decode($et->remark_mobiles,1));
        $et->user = (new Model('qy_user_list'))->find(['id'=>$et->user_id]);
        if(!$et->id){
            die('未知客户');
        }
        if($et->user_id != $r_user_id){
            $et->r_user_id = $r_user_id;
        }
        $qyEtGroupchat = (new Model('qy_et_groupchat'))->where(['wid'=>$wid])->list_all();
        $groupchat = [];
        foreach($qyEtGroupchat as $qyetgroupchat){
            $member_list = json_decode($qyetgroupchat->member_list,1);
            foreach($member_list as $member){
                if($member['userid'] == $et->external_userid){
                    $groupchat[] = $qyetgroupchat;
                }
            }
        }
        $etAll = (new Model('qy_externalcontact_list'))->where(['id@!='=>$etId,'wid'=>$wid,'external_userid'=>$et->external_userid])->list_all();
        foreach($etAll as $k=>$v){
            $etAll[$k]->tags = json_decode($v->tags,1);
            $etAll[$k]->custom = json_decode($v->custom_information,1);
            $etAll[$k]->remark_mobiles = implode(",",json_decode($v->remark_mobiles,1));
            $etAll[$k]->user = (new Model('qy_user_list'))->find(['id'=>$v->user_id]);
            if($r_user_id != $v->user_id){
                $etAll[$k]->r_user_id = $r_user_id;
            } 
            $data = (new Model('user_fields'))->where(['wid'=>$wid,'user_id'=>$v->id])->list_all();
            $fis = (new Model("qy_custom_fields"))->where(["wid"=>$wid])->order('orders asc')->list_all();
            foreach ($fis as $keys => $values) {
                foreach ($data as $key => $user_v) {
                    if($user_v->fields_id == $values->id){
                        $fis[$keys]->is_x = 1;
                        $fis[$keys]->contents = $user_v->content;
                    }
                }
                if($r_user_id != $v->user_id){
                    $fis[$keys]->r_user_id = $r_user_id;
                }
                $fis[$keys]->content = json_decode($values->content,1);
                $fis[$keys]->user_id = $v->id;
                $fis[$keys]->wid = $wid;
            }
            $etAll[$k]->fields = json_encode($fis);
        }
        $qyEtDynamic = (new Model('qy_et_dynamic'))->where(['wid'=>$wid,'external_userid'=>$et->external_userid])->order('ctime desc')->list_all_array();
        $etDynamic = [];
        foreach($qyEtDynamic as $qyetdynamic){
            $etDynamic[date('m_d',$qyetdynamic['ctime'])][] = $qyetdynamic;
        }
        $h = Helper::getInstance();
        $etTagArr = $h->get_et_tags($wid);
        $addWayArr = $h->add_way_arr();
        $user_con = json_decode($et->custom_information,1);
        $user_fields = (new Model('user_fields'))->where(['wid'=>$wid,'user_id'=>$etId])->list_all();
        $fields = (new Model("qy_custom_fields"))->where(["wid"=>$wid])->order('orders asc')->list_all();
        foreach ($fields as $keys => $values) {
            foreach ($user_fields as $key => $user_v) {
                if($user_v->fields_id == $values->id){
                    $fields[$keys]->is_x = 1;
                    $fields[$keys]->contents = $user_v->content;
                }
            }
            if($et->user_id != $r_user_id){
                $fields[$keys]->r_user_id = $r_user_id;
            }
            $fields[$keys]->content = json_decode($values->content,1);
            $fields[$keys]->user_id = $etId;
            $fields[$keys]->wid = $wid;
        }
        $et->fields = json_encode($fields);
        $this->assign("et", $et);
        $this->assign("etAll", $etAll);
        $this->assign("r_user_id", $r_user_id);
        $this->assign("fields", $fields);
        $this->assign("message", $message);
        $this->assign("user_con", $user_con);
        $this->assign("etTagArr", $etTagArr);
        $this->assign("addWayArr", $addWayArr);
        $this->assign("groupchat", $groupchat);
        $this->assign("etDynamic", $etDynamic);
        $this->assign("h", $h);
        return $this->show();
    }


      public function upd_user_fields(){
        setApi();
        $wid = $_POST["wid"];
        $user_id = $_POST["user_id"];
        $id = $_POST["id"];
        $content = $_POST["content"];
        $user_fields = (new Model('user_fields'))->find(['wid'=>$wid,'user_id'=>$user_id,'fields_id'=>$id]);
        if(!$user_fields->id){
            $user_fields = new Model('user_fields');
            $user_fields->wid = $wid;
            $user_fields->user_id = $user_id;
            $user_fields->fields_id = $id;
        }
        $user_fields->content = $content;
        if($user_fields->save()){
            sendSuccess("修改成功");
        }
        sendError("修改失败");
    }


        public function update_tag(){
        setApi();
        $title = \Request::post('title');
        $type = \Request::post('type');
        $id = \Request::post('id');
        $larel_name = \Request::post('name');
        $name = \Request::post('name');
        $et = (new Model('qy_externalcontact_list'))->find($id);
        $wid = $et->wid;
        $qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
        // $replyConfig = (new Model('qy_reply_config'))->find(['wid'=>$wid]);
        $replyConfig = Helper::getInstance()->get_message_send_config($wid);
        $app = QyWechatApi::getInstance()->get_qy_agent_app($qyConfig->corp_id,$replyConfig->agent_id,$replyConfig->secret);
        $accessToken = $app->access_token;
        $token = $accessToken->getToken()['access_token'];
        if($et->custom_information == ""){
            $arr = ['qq'=>null,'birthday'=>null,'age'=>null,'email'=>null,'weibo'=>null,'address'=>null];
            $et->custom_information = json_encode($arr,320);
            $et->save();
        }
        $desc = json_decode($et->custom_information,1);
        foreach ($desc as $key => $value) {
            if($key == $type && $title == $value){
                sendError($name."未修改");
            }else if($key == $type){
                $desc[$key] = $title;
            }
        }
        if($larel_name){
            $et->level_manager_id = $larel_name;
            $et->save();
        }
        if($type == "remark_mobiles"){
            $mobile = explode(",", $title);
            foreach ($mobile as $key => $value) {
                if(strlen($value) != 11){
                    sendError("请输入正确的11位手机号码");
                }
            }
            $user = (new Model("qy_user_list"))->find(["id"=>$et->user_id]);
            $body = \HttpCurl::post(
                "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/remark?access_token=".$token,
                json_encode([
                    "userid"=>$user->userid,
                    "external_userid"=>$et->external_userid,
                    "remark_mobiles"=>$mobile
                ])
             );
            $resp_arr = json_decode($body, 1);
            if($resp_arr["errmsg"] == "ok"){
                $mobiles = json_encode(explode(",", $title),320);
                $et->remark_mobiles = $mobiles;
            }else{
                sendError("手机号码格式不合法");
            }
        }else if($type == "description"){
            if($et->description == $title){
                sendError($name."未修改");
            }
            $et->description = $title;
        }
        $et->custom_information = json_encode($desc,320);
        $et->save();
        sendSuccess($name.'修改成功');
    }

}